package alps.common.widget;

import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

import alps.common.R;

/**
 * 以五角星表示分数
 * @author alps
 *
 */
public class SimpleRatingBar {
    
    private LinearLayout mRootView;
    
    private final int MAX_COUNT = 5;
    
    public SimpleRatingBar(LinearLayout root) {
        mRootView = root;
    }
    
    public void setScore(float score) {
        if (score < 0) {
            score = 0;
        }
        if (score > MAX_COUNT) {
            score = MAX_COUNT;
        }
        mRootView.removeAllViews();
        int count = 0;
        
        LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.weight = 1;
        
        count = (int) score;
        for (int i = 0; i < count; i++) {
            ImageView iv = createImageView();
            iv.setAdjustViewBounds(true);
            iv.setImageResource(R.drawable.icon_star_on);
            mRootView.addView(iv, params);
        }
        
        float rest = score - count;
        if (rest >= 0.5) {
            count ++;
            ImageView iv = createImageView();
            iv.setImageResource(R.drawable.icon_star_on);
            mRootView.addView(iv, params);
        }
        
        int restCount = MAX_COUNT - count;
        for (int i = 0; i < restCount; i++) {
            ImageView iv = createImageView();
            iv.setImageResource(R.drawable.icon_star_off);
            mRootView.addView(iv, params);
        }
    }
    
    private ImageView createImageView() {
        ImageView iv = new ImageView(mRootView.getContext());
        iv.setAdjustViewBounds(true);
        
        return iv;
    }
}
